import { CrsClient } from "../../crsClient"
import { config } from "../../config"

const systemInfo = wx.getSystemInfoSync()

const SELECT_TYPE = {
  NONE: 0,
  IMAGE: 1,
  VIDEO: 2,
}
const App = getApp()
Page({
  data: {
    src: "",
    downImagePath: "",
    img: "",
    codePath: "",
    windowWidth: 0,
    windowHeight: 0,
    showOverlay: true,
    showSelect: false,
    SELECT_TYPE: SELECT_TYPE,
    selectType: 0,
    imgIndex: 1,
    imgList: [],
    on: true, // 控制音乐的状态，以及图标是否旋转
    showLoading: true,
    showLoadingText: "加载中",
    musicList: [
      {
        title: "音乐1",
        src: config.api_blink_url + "/train-music1.mp3",
        id: 0,
      },
      {
        title: "音乐2",
        src: config.api_blink_url + "/train-music2.mp3",
        id: 1,
      },
      {
        title: "音乐3",
        src: config.api_blink_url + "/train-music3.mp3",
        id: 2,
      },
    ],
  },

  /** @type {CameraFrameListener} 相机帧回调 */
  listener: undefined,
  /** @type {HTMLCanvasElement} canvas对象 */
  canvas: undefined,

  /** @type {boolean} 是否需要持续识别，在点击“识别体验”之后和识别成功之前为true */
  runningCrs: undefined,
  /** @type {boolean} 当前是否正在进行CRS请求 */
  busy: undefined,
  /** @type {CrsClient} 负责发起CRS请求的对象 */
  crsClient: undefined,
  /** @type {number} 最后一次CRS请求的事件，用于判断是否满足最短请求间隔 */
  last: undefined,

  onLoad: function () {
    setTimeout(() => {
      this.setData({
        showLoading: false,
      })
      this.selectComponent("#music-cmp").initMusic(0)
      this.saveSignRecord()
    }, 4000)
  },
  onReady: function () {
    // // 获取BackgroundAudioManager 实例
    // this.back = wx.getBackgroundAudioManager()
    // // 对实例进行设置
    // this.back.src = config.api_blink_url + "/train-music1.mp3"
    // this.back.title = "火车" // 标题为必选项
    // this.back.play() // 开始播放
    // // this.back.loop = true
    // this.back.onEnded((res) => {
    //   this.back.src = config.api_blink_url + "/train-music1.mp3"
    //   this.back.title = "火车" // 标题为必选项
    //   this.back.play()
    // })
    this.ctx = wx.createCameraContext()
    this.getInfo()
    this.downImage()
  },
  tip(){
    wx.showToast({
      title: '打卡成功',
      icon: 'loading',
      duration: 2000
    })
    setTimeout(function(){
      wx.hideToast()
    },3000)
   },
   saveSignRecord(){//打卡成功
    wx.request({
      url: `https://www.pdjlixiang.com/cip-rest/thirdParty/saveSignRecord`,
      method: "post",
      data:{
        openid:App.globalData.uid,
        code:'SGLC'
      },
      header: {
        'content-type': 'application/x-www-from-urlencoded',
        'token':App.globalData.token
      },
      success: (res) => {
        console.log(res)
        this.tip()
      }
    })
   },
  onJumpMin() {
    wx.navigateToMiniProgram({
     appId: 'wxe9bc7c69463b5455', // 需要跳转到指定的小程序appid
     path: '',   // 打开的页面
     envVersion: 'release',
     success(res) {
      // 打开成功
      console.log(res);
     }
    })
   },
  showLoading(text) {
    this.setData({
      showLoading: true,
      showLoadingText: text,
    })
  },
  hideLoading() {
    this.setData({
      showLoading: false,
    })
  },
  getInfo: function () {
    var _this = this
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight,
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  //图像识别部分：

  onShow: function () {
    if (this.listener) this.listener.start() //页面隐藏时相机帧的监听会自动停止，但恢复展示时不会自动启动，这里手动启动
  },

  onCameraInit: function () {
    //找到canvas对象
    const query = wx.createSelectorQuery()
    query
      .select("#capture")
      .fields({ node: true })
      .exec((res) => {
        const canvas = res[0].node
        //设置canvas内部尺寸为480*640，frame-size="medium"的设置下相机帧大多是480*640
        canvas.width = 480
        canvas.height = 640
        this.canvas = canvas

        this.crsClient = new CrsClient(this.data.config, this.canvas)

        //开始监听相机帧
        let cameraContext = wx.createCameraContext()
        this.listener = cameraContext.onCameraFrame((frame) => {
          if (!this.canvas) return
          let canvas = this.canvas
          //如果尺寸不匹配，就修改canvas尺寸以适应相机帧
          if (canvas.width !== frame.width || canvas.height !== frame.height) {
            canvas.width = frame.width
            canvas.height = frame.height
          }

          //this.queryImage(frame)
        })
        this.listener.start()
      })
  },

  queryImage: function (frame) {
    if (!this.runningCrs || this.busy || !this.crsClient) return

    //最短的两次CRS请求间隔
    let now = new Date().getTime()
    if (this.last && now - this.last < this.data.config.minInterval) return
    this.last = now

    this.busy = true //如果正在进行CRS请求，就不允许再次请求

    this.crsClient
      .queryImage(frame)
      .then((res) => {
        if (!this.runningCrs) return //避免在停止后仍然触发
        let result = res && res.result
        if (!result) return

        if (result.target) {
          console.log("识别成功", result.target.targetId)
          //如果待触发的id列表中存在识别到的这个id，就触发
          if (
            this.data.targetIds.find(
              (targetId) => targetId === result.target.targetId
            )
          ) {
            this.onResult(result.target)
          }
        } else {
          console.log("识别失败", result.message)
        }
        this.busy = false
      })
      .catch((e) => {
        this.busy = false
        console.log(e)
      }) //小程序iOS端不支持finally，所以在then和catch里分别设置busy = false
  },
  //截图
  downImage() {
    var that = this
    wx.downloadFile({
      // url: "https://www.pdjlixiang.com:8801/assets/bg.png",
      url: "https://www.pdjlixiang.com:8801/assets/HC-Share.png",
      success(res) {
        console.log(res.tempFilePath)
        that.setData({
          downImagePath: res.tempFilePath,
        })
      },
    })
    wx.downloadFile({
      // url: "https://www.pdjlixiang.com:8801/assets/bg.png",
      url: "https://www.pdjlixiang.com:8801/assets/ScanCode.jpg",
      success(res) {
        that.setData({
          codePath: res.tempFilePath,
        })
      },
    })
  },
  takePhoto() {
    var that = this
    wx.showLoading({
      title: "截图中..",
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 6000)
    that.ctx.takePhoto({
      quality: "high",
      success: (res) => {
        console.log(res)
        var temp = res.tempImagePath
        this.setData({
          src: temp,
        })
        console.log(temp)
        //相当于h5的获取ID值
        const cts = wx.createCanvasContext("photos")
        // console.log(cts)
        cts.drawImage(temp, 0, 0, this.data.windowWidth, this.data.windowHeight)
        cts.drawImage(
          this.data.downImagePath,
          0,
          0,
          this.data.windowWidth,
          this.data.windowHeight
        )
        cts.drawImage(this.data.codePath, 5, 5, 50, 50)
        cts.draw(false, () => {
          that.draw()
        })
      },
    })
  },
  draw() {
    wx.canvasGetImageData({
      canvasId: "photos",
      x: 0,
      y: 0,
      width: this.data.windowWidth,
      height: this.data.windowHeight,
      success(res) {
        console.log(res)
        //比较重要的代码
        const upng = require("../../UPNG")
        let png = upng.encode([res.data.buffer], res.width, res.height)
        let base64 = wx.arrayBufferToBase64(png)
        console.log(base64)
        var aa = wx.getFileSystemManager()

        aa.writeFile({
          filePath: wx.env.USER_DATA_PATH + "/test.png",
          data: base64,
          encoding: "base64",
          success: (res) => {
            wx.saveImageToPhotosAlbum({
              filePath: wx.env.USER_DATA_PATH + "/test.png",
              success: function (res) {
                wx.showToast({
                  title: "保存成功",
                })
              },
              fail: function (err) {
                console.log(err)
              },
            })
            console.log(res)
          },
          fail: (err) => {
            console.log(err)
          },
        })
      },
    })
  },
  //音乐控制
  musicControl: function () {
    this.setData({ on: !this.data.on })
    // if (this.data.on) {
    //   this.back.play()
    // } else {
    //   this.back.pause()
    // }
    this.selectComponent("#music-cmp").soundControl(this.data.on)
  },
  onShareAppMessage: function () {
    return {
      title: "微信AR", // 转发标题
      path: "pages/train/index", // 自定义页面路径中携带的参数，可带参数 如 path?a=1&b=2 的 “?” 后面部分
      imageUrl: "", //使用默认截图, 自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径。支持PNG及JPG。显示图片长宽比是 5:4
    }
  },
  onResult: function (target) {},
})
